import os
from collections.abc import Sequence
from dataclasses import dataclass
from typing import override

from ..utils import SheetColumnsExtractor
from .document import Document
from .interface import Unmarshaler

__all__ = ["User", "UserStage", "UserUnmarshaler"]


@dataclass(frozen=True)
class User(object):
    username: str
    posts: list[Document]


@dataclass(frozen=True)
class UserStage(object):
    users: Sequence[User]


class UserUnmarshaler(Unmarshaler[UserStage]):
    """
    Unmarshaler for the `UserStage`.
    """

    _extractor: SheetColumnsExtractor

    def __init__(self, *, path: os.PathLike, username_column: str, content_column: str) -> None:
        self._extractor = SheetColumnsExtractor(
            path=path,
            columns=(username_column, content_column),
        )

    @override
    def unmarshal(self) -> UserStage:
        deduplicated_posts: dict[str, list[Document]] = {}
        for username, content in self._extractor.extract():
            if username not in deduplicated_posts:
                deduplicated_posts[username] = []
            deduplicated_posts[username].append(content)

        users = []
        for username, posts in deduplicated_posts.items():
            users.append(User(username, posts))
        return UserStage(users)
